﻿using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Security;
using StudySystem.MainLogic.Others;
using StudySystem.SQLServer;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace StudySystem.MainLogic.Items
{

    public class ClassQuestion
    {   
        private const int ExcelValidCol = 2;
        private string _questionID;
        private string _subjectID;
        private string _questionContent;
        private string _answer;
        private List<ClassRecord> _records;
        private float _accuracy;

        public string QuestionID { get => _questionID; set => _questionID = value; }
        public string SubjectID { get => _subjectID; set => _subjectID = value; }
        public string QuestionContent { get => _questionContent; set => _questionContent = value; }
        public string Answer { get => _answer; set => _answer = value; }
        public List<ClassRecord> Records { get => _records; set => _records = value; }
        public float Accuracy { get => CalculateAccuracy(CalculateTimes()); set => _accuracy = value; }

        public ClassQuestion(DataRow dr)
        {
            QuestionID = dr["QuestionID"].ToString();
            SubjectID = dr["SubjectID"].ToString();
            QuestionContent = dr["QuestionContent"].ToString();
            Answer = dr["Answer"].ToString();
            this.Records = GetAllRecords();
            this.Accuracy = CalculateAccuracy(CalculateTimes());
        }

        public static List<List<ClassQuestion>> SortQuestion(DataTable dt)
        {
            List<List<ClassQuestion>> listQues = new List<List<ClassQuestion>>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                bool isExist = false;//标记当前dr中的问题的学科是否在list<list>中存在
                if (listQues.Count > 0)
                {
                    for (int j = 0; j < listQues.Count; j++)
                    {
                        List<ClassQuestion> qList = listQues[j];
                        if (dr["SubjectID"].ToString() == qList[0].SubjectID)
                        {
                            qList.Add(new ClassQuestion(dr));
                            isExist = true;
                            break;
                        }
                    }
                    if (isExist == false)
                    {
                        List<ClassQuestion> questions = new List<ClassQuestion>();
                        questions.Add(new ClassQuestion(dr));
                        listQues.Add(questions);
                    }
                }
                else
                {
                    List<ClassQuestion> questions = new List<ClassQuestion>();
                    questions.Add(new ClassQuestion(dr));
                    listQues.Add(questions);
                }
            }
            return listQues;
        }

        /// <summary>
        /// 找到当前对象所在的list
        /// 用于删除或其它功能
        /// </summary>
        /// <returns></returns>
        public List<ClassQuestion> FindQuesList()
        {
            foreach (List<ClassQuestion> qList in UserManagement.listQuestions)
            {
                if (this.SubjectID == qList[0].SubjectID)
                {
                    return qList;
                }

            }
            return null;
        }


        public static void InsertAQuestion(string subjectID, string question, string answer)
        {
            //更新数据库
            DBForQuestion.InsertAQuestion(subjectID, question, answer);
            //更新dt
            DBForQuestion.GetQuestion(ref UserManagement.ds);
            //更新list
            UserManagement.listQuestions = SortQuestion(UserManagement.ds.Tables["QuestionTable"]);
        }

        public void DeleteQuestion()
        {
            //删除数据库中的数据  更新数据库
            DBForQuestion.DeleteAQuestion(this.QuestionID);
            //更新list<list>
            List<ClassQuestion> qList = FindQuesList();
            qList.Remove(this);
            //ds不用更新
        }

        public void ModifyAQuestion(string newQuestion, string newAnswer)
        {
            //更新数据库
            DBForQuestion.ModifyAQuestion(this.QuestionID, newQuestion, newAnswer);
            //更新list
            this.QuestionContent = newQuestion;
            this.Answer = newAnswer;
            //不用更新ds
        }

        /// <summary>
        /// 将Excel中的第一列（问题）和第二列（答案）存到DataTable中
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static DataTable ExcelToQuestionTable(string fileName, string sheetName)
        {
            ISheet sheet = null;
            DataTable data = UserManagement.ds.Tables["QuestionTable"].Clone();
            int startRow = 0;
            FileStream fs = null;
            IWorkbook workbook = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = ExcelValidCol; //总的有效的列数

                    //最后一行的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null && j == 0) //同理，没有数据的单元格都默认是null
                                dataRow["QuestionContent"] = row.GetCell(j).ToString();
                            else if (row.GetCell(j) != null && j == 1)
                            {
                                dataRow["Answer"] = row.GetCell(j).ToString();
                            }
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
            finally
            {

            }
        }

        public static void BulkInsertQuestions(DataTable dt, string subjectID)
        {
            if (dt == null)
                return;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                InsertAQuestion(subjectID, dr["QuestionContent"].ToString(), dr["Answer"].ToString());
            }
        }

        public List<ClassRecord> GetAllRecords()
        {
            List<ClassRecord> records = new List<ClassRecord>();
            DBForRecord.SelectAllRecords(ref UserManagement.ds,QuestionID);
            foreach (DataRow dr in UserManagement.ds.Tables["recordTable"].Rows)
            {
                records.Add(new ClassRecord(dr));
            }
            return records;
        }

        public string ShowRecord()
        {
            string ret = "此题目前没有答题记录！";
            if(Records.Count > 0)
            {
                int[] times = CalculateTimes();
                ret = "共回答问题" + Records.Count + "次，" +
                    "正确" + times[0] + "次，" +
                    "模糊" + times[1] + "次，" +
                    "错误" + times[2] + "次。";
            }
            return ret;
        }

        public int[] CalculateTimes()
        {
            int recordCount = Records.Count;
            //ret[0]  正确次数
            //ret[1]  模糊次数
            //ret[2]  错误次数
            int[] ret = new int[] { 0, 0, 0 };
            if (recordCount == 0)
            {
                return ret;
            }
            foreach(ClassRecord r in Records)
            {
                switch (r.AnswerResult)
                {
                    case AnswerResult.WRONG:
                        ret[2]++;
                        break;
                    case AnswerResult.VAGUE:
                        ret[1]++;
                        break;
                    case AnswerResult.RIGHT:
                        ret[0]++;
                        break;
                    default:
                        break;
                }
            }
            return ret;
        }

        public static List<ClassQuestion> SearchOneSubjectQues(ClassSubject subject, string searchContent)
        {
            List<ClassQuestion> ret = new List<ClassQuestion>();
            List<ClassQuestion> questions = subject.Questions;
            foreach (ClassQuestion q in questions)
            {
                if(q.Answer.Contains(searchContent) || q.QuestionContent.Contains(searchContent))
                {
                    ret.Add(q);
                }
            }
            return ret;
        }

        public static List<ClassQuestion> SearchAllSubjectQues(string searchContent)
        {
            List<ClassQuestion> ret = new List<ClassQuestion>();
            foreach (ClassSubject s in UserManagement.subjects)
            {
                ret.AddRange(SearchOneSubjectQues(s, searchContent));
            }
            return ret;
        }

        public float CalculateAccuracy(int[] records)
        {
            float ret = 0.0f;
            int times = Utilities.Sum(records);
            if (times == 0)
                return ret;
            else
            {
                ret = (float)((records[0] * 1.0f + records[1] * 0.5f) / times);
            }
            
            return ret;
        }

    }
}
